import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/ui/route/worksdo/type26_my_workorder/treasury/ui/ui_form.dart';
import '../../../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../../../http/bean/worksdo/hardware_collar_bean.dart';
import '../../../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../../../http/model/hardware_collar_model.dart';
import '../../../../../app_ui.dart';

///五金领用列表
class UiForm1 {
  static RollerBean? Hardwaretype = null; //五金种类
  static RollerBean? Hardwarename = null; //五金名称
  static _Presenter? _presenter = null;

  static clear() {
    Hardwaretype = null;
    Hardwarename = null;
    _presenter?.datas?.clear();
    _presenter?.datas = null;
    _presenter = null;
  }

  ///isQuest 是否请求数据。
  static Widget build(
      BuildContext context,
      EquipmentResponseData? equipmentResponseData,
      bool isQuest,
      StateSetter? bodyStateBody,
      {String? title,
      ResponseCallbackWithVoid? callbackWithVoid}) {
    EquipmentInfo? materialInfo = equipmentResponseData?.equipmentInfo;
    if (_presenter == null) {
      _presenter = _Presenter();
    }
    _presenter?.equipmentResponseData = equipmentResponseData;
    // if (isQuest) {
    //   Future.delayed(Duration(milliseconds: 200)).then((e) {
    //     //延迟获取比较好。防止页面没加载完成。导致网络进度条无法正常关闭。
    //     // print(
    //     //     "_setState: ${UiForm1?._setState}\tsetStateBody :${_presenter?.setStateBody}");
    //     _presenter?.GetListForPicking(context, callbackWithBool: (value) {
    //       // if (value) {//这里不需要刷新，请求方法里，有刷新。
    //       //   bodyStateBody?.call(() {}); //主界面刷新。
    //       //   _presenter?.setStateBody?.call((){});
    //       // }
    //     }); //获取五金列表
    //   });
    // }
    return StatefulBuilder(builder: (context, setState) {
      _presenter?.setStateBody = setState;
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).Listofequipmentengineers; //设备工程师名单
      }
      // children.add(UiBase.title(context, title,
      //     bottom: AppEdgeInsets.margin_bottom)); //标题
      var leftBtn = LibUi.outlineDrpButton("${Hardwaretype?.value ?? ""}",
          minWidth: 80, maxWidth: 95, onPressed: () {
        _presenter?.GetPickMaterType(context, callback: (value) {
          AppDialog.showDialogWithRollerPicker(context,
                  datas: value, data: Hardwaretype)
              .then((value) {
            if (value != null) {
              setState(() {
                //界面重新刷新。
                if (Hardwaretype?.key != value?.key) {
                  //类型选择发生改变；
                  Hardwarename = null;
                  _presenter?.nameDatas?.clear(); //五金名称数据重置。
                }
                Hardwaretype = value; //五金类型
                _presenter?.GetListForPicking(context); //获取五金列表
                callbackWithVoid?.call();
              });
            }
          });
        });
      });
      var leftRow = Row(
        children: [Text(AppStrings.of(context).Hardwaretype2 + ":"), leftBtn],
      ); //五金类型
      var rightBtn = LibUi.outlineDrpButton("${Hardwarename?.value ?? ""}",
          minWidth: 80, maxWidth: 95, onPressed: () {
        _presenter?.GetMaterialForPicking(context, callback: (value) {
          AppRouteHelper.goSearchNameRoute(context, value, (value) {
            setState(() {
              Hardwarename = value; //五金名称
              _presenter?.GetListForPicking(context); //获取五金列表
              callbackWithVoid?.call();
            });
          });
        });
      });
      var rightRow = Row(
        children: [Text(AppStrings.of(context).Hardwarename + ":"), rightBtn],
      ); //五金名称
      var tRow =
          Row(children: [Expanded(child: leftRow), Expanded(child: rightRow)]);
      children.add(tRow);
      children.add(_table(context, materialInfo!));
      var column = UiBase.column(context, children);
      // var card = UiCard.build(context, column);
      // return card;
      return Container(
        child: column,
        color: Colors.white,
      );
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _tableSetState = null;

  static Widget _table(BuildContext context, EquipmentInfo materialInfo) {
    if (materialInfo == null) {
      return LibUi.getEmptyView();
    }
    // return LibUi.getEmptyView();
    //fixme 表格
    return StatefulBuilder(builder: (context, setState) {
      _tableSetState = setState;
      //可以水平滑动的表格
      var scrolltable = _scrolltable(context, _presenter?.datas);
      //水平滑动效果
      var singleChildScrollView = SingleChildScrollView(
          child: scrolltable, scrollDirection: Axis.horizontal);
      return Center(
        child: Container(
          alignment: Alignment.centerLeft,
          child: singleChildScrollView,
          width: px.screenWidth(),
        ),
      );
    });
  }

  ///水平滑动表格
  static Widget _scrolltable(BuildContext context, List<HardwareBean>? datas) {
    if (datas == null || datas!.length <= 0) {
      return AppUi.getEmptyView();
    }
    var children = <TableRow>[];
    //第一行标题栏
    List<Widget> titleChildren = [];
    titleChildren.add(_text(AppStrings.of(context).TheSerial)); //序号
    titleChildren.add(_text(AppStrings.of(context).Hardwarename)); //五金名称
    titleChildren.add(_text(AppStrings.of(context).Quantityreceived)); //领用数量
    titleChildren.add(_text(AppStrings.of(context).Quantityreceived2)); //实际领用数量
    titleChildren
        .add(_text(AppStrings.of(context).Quantityremaininginstock)); //仓库剩余数量
    titleChildren.add(_text(AppStrings.of(context).cangwei)); //仓位
    titleChildren.add(_text(AppStrings.of(context).Width_Height)); //规格型号
    titleChildren.add(_text(AppStrings.of(context).BasicNumUnit)); //单位数量
    titleChildren.add(_text(AppStrings.of(context).ManufacturerName)); //品牌
    titleChildren.add(_text(AppStrings.of(context).EquipmentName)); //关联设备
    titleChildren.add(_text(AppStrings.of(context).Remarks)); //备注
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: titleChildren);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      List<Widget> rowChildren = [];
      //序号
      var TheSerial = _text("${i + 1}");
      rowChildren.add(TheSerial);
      //五金名称
      var MaterialName = _text("${data.name}");
      rowChildren.add(MaterialName);
      StateSetter? PlanBasicNumSetState = null; //领用数量
      StateSetter? PlanBasicNum2SetState = null; //实际领用数量
      //领用数量（用户手输）
      var PlanBasicNum = StatefulBuilder(builder: (context, setState) {
        PlanBasicNumSetState = setState;
        var PlanBasicNum = UiBase.itemWithSigleEdit(
            context, "${data?.DefUnitNum}",
            isAllowEmpty: true,
            isDecimal: true,
            isNegative: false,
            unit: data?.getDefUnitName(),
            max: data?.getDefUnitMax(),
            isLine: true, onChanged: (value) {
          // print("文本变化：$value");
          data?.DefUnitNum = value;
          data?.auotSumBasicNum2();
          PlanBasicNum2SetState?.call(() {});
        });
        return PlanBasicNum;
      });
      rowChildren.add(PlanBasicNum); //fixme 领用数量
      //实际领用数量:基本单位（自动计算）
      var PlanBasicNum2 = StatefulBuilder(builder: (context, setState) {
        PlanBasicNum2SetState = setState;
        var PlanBasicNum2 =
            UiBase.itemWithSigleEdit(context, "${data?.sumBasicNum2}",
                isAllowEmpty: true,
                isDecimal: true,
                isNegative: false,
                unit: data?.BasicUnit,
                max: data?.sumBasicNum,
                readOnly: true,
                //fixme 自动计算，屏蔽掉用户输入。
                isLine: true, onChanged: (value) {
          // print("文本变化：$value");
          data?.sumBasicNum2 = value;
          data?.auotDefUnitNum();
          PlanBasicNumSetState?.call(() {});
        });
        return PlanBasicNum2;
      });

      rowChildren.add(PlanBasicNum2); //fixme 实际领用数量
      // 仓库剩余数量
      var Quantityremaininginstock = _text("${data.getsumBasicNum()}");
      rowChildren.add(Quantityremaininginstock);
      //仓位
      var code = _text("${data.code?.trim()}");
      rowChildren.add(code);
      //规格型号
      var MaterialType = _text("${data.Size?.trim()}");
      rowChildren.add(MaterialType);
      //单位数量
      var profession = _text("${data.getUnitNum()}");
      rowChildren.add(profession);
      //品牌
      var ManufacturerName = _text("${data.ManufacturerName}");
      rowChildren.add(ManufacturerName);
      //关联设备
      var EquipmentName = _text("${data.EquipmentName}");
      rowChildren.add(EquipmentName);
      //备注
      var note = _text("${data.note}");
      rowChildren.add(note);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: IntrinsicColumnWidth(),
        1: IntrinsicColumnWidth(),
        2: IntrinsicColumnWidth(),
        3: IntrinsicColumnWidth(),
        4: IntrinsicColumnWidth(),
        5: IntrinsicColumnWidth(),
        6: IntrinsicColumnWidth(),
        7: IntrinsicColumnWidth(),
        8: IntrinsicColumnWidth(),
        9: IntrinsicColumnWidth(),
        10: IntrinsicColumnWidth(),
        11: IntrinsicColumnWidth(),
        12: IntrinsicColumnWidth(),
        13: IntrinsicColumnWidth(),
        14: IntrinsicColumnWidth(),
        15: IntrinsicColumnWidth(),
        16: IntrinsicColumnWidth(),
        17: IntrinsicColumnWidth(),
        18: IntrinsicColumnWidth(),
        19: IntrinsicColumnWidth(),
      },
      children: children,
    );
    return table;
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(String? text, {bool isStart = false}) {
    // return Center(
    //   child: Text(text ?? ""),
    // );
    Widget child;
    if (isStart) {
      var textKey = Text(
        text ?? "",
        style: AppStyle.textStyleWithCard(),
      );
      var value = "*";
      var startText = Text(
        value,
        softWrap: true,
        style: AppStyle.textStyleWithCardRed(),
      );
      child = SizedBox(
        child: Row(
          children: [textKey, startText],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        width: 120,
      );
    } else {
      child = Text(text ?? "");
    }
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
            minHeight: 36.0, //最小高度
            minWidth: 65),
        child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(left: 8, right: 8),
          child: child,
        ),
      ),
    );
  }

  //复选框
  //isChecked 是否选中
  //isEnable 是否可操作
  //onChanged 选中回调
  static Widget _checkbox(bool isChecked,
      {bool isEnable = true, Function(bool)? onChanged}) {
    Color activeColor = Colors.blueAccent;
    Color inactiveColor = Colors.black;
    if (!isEnable) {
      //不可用，颜色变暗。
      activeColor = Colors.black12;
      inactiveColor = Colors.black12;
    }
    return Container(
      alignment: Alignment.center,
      // height: 30,
      // width: 30,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      child: CircleCheckbox(
        isEnable: isEnable,
        value: isChecked,
        //value 是否选中
        width: 20,
        //width 宽度
        height: 20,
        //height 高度
        activeColor: activeColor,
        //activeColor 选中时背景颜色
        inactiveColor: inactiveColor,
        //inactiveColor 未选中时颜色
        style: CircleCheckboxStyle.tick_hollow,
        //circle_point 圆点样式
        //checked: , 自定义选中组件；fixme 优先级比以上属性设置要高。
        //unChecked: ,自定义未选中组件
        onChanged: (bool) {
          //选中状态改变时回调，如点击时。
          //选中状态改变时回调。
          //setState(() {});
          if (isEnable) {
            onChanged?.call(bool);
          }
        },
      ),
    );
  }
}

class _Presenter {
  EquipmentResponseData? equipmentResponseData;

  ///body视图状态
  StateSetter? setStateBody;

  //五金类型
  List<RollerBean>? typeDatas = [];

  GetPickMaterType(BuildContext context,
      {ResponseCallbackWithT<List<RollerBean>>? callback = null}) {
    if (typeDatas != null && typeDatas!.length > 0) {
      callback?.call(typeDatas!);
      return;
    }
    HardwareCollarModel.GetPickMaterType(context, true, onError: (code, error) {
      AppDialog.showDialogWithError(context, code, error)?.then((value) {
        AppRouteHelper.pop(context); //网络异常，关闭当前页面
      });
    })?.then((value) {
      if (value.isSuccessForCode()) {
        try {
          var datas = value.Data?.datas;
          var length = datas?.length ?? 0;
          if (length <= 0) {
            AppDialog.showDialogWithInfo(context,
                    content: AppStrings.of(context).noData) //暂无数据
                ?.then((value) {});
          } else {
            // setStateBody?.call(() {});
            typeDatas = datas;
            callback?.call(datas!);
          }
        } catch (e) {}
      } else {
        //异常
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
            ?.then((value) {});
      }
    });
  }

  //五金名称
  List<RollerBean>? nameDatas = [];

  GetMaterialForPicking(BuildContext context,
      {ResponseCallbackWithT<List<RollerBean>>? callback = null}) {
    if (nameDatas != null && nameDatas!.length > 0) {
      callback?.call(nameDatas!);
      return;
    }
    HardwareCollarModel.GetMaterialForPicking(
        context, UiForm1.Hardwaretype?.key ?? "", true, onError: (code, error) {
      AppDialog.showDialogWithError(context, code, error)?.then((value) {
        AppRouteHelper.pop(context); //网络异常，关闭当前页面
      });
    })?.then((value) {
      if (value.isSuccessForCode()) {
        try {
          var datas = value.Data?.datas;
          var length = datas?.length ?? 0;
          if (length <= 0) {
            AppDialog.showDialogWithInfo(context,
                    content: AppStrings.of(context).noData) //暂无数据
                ?.then((value) {});
          } else {
            // setStateBody?.call(() {});
            nameDatas = datas;
            callback?.call(datas!);
          }
        } catch (e) {}
      } else {
        //异常
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
            ?.then((value) {});
      }
    });
  }

  //五金列表数据
  List<HardwareBean>? datas = null;

  ///五金列表
  GetListForPicking(BuildContext context,
      {ResponseCallbackWithBool? callbackWithBool}) {
    String Matertype = UiForm1.Hardwaretype?.key ?? "";
    String MaterCode = UiForm1.Hardwarename?.key ?? "";
    HardwareCollarModel.GetListForPicking(context, Matertype, MaterCode, true,
        onError: (code, error) {
      AppDialog.showDialogWithError(context, code, error)?.then((value) {
        AppRouteHelper.pop(context); //网络异常，关闭当前页面
      });
    })?.then((value) {
      if (value.isSuccessForCode()) {
        try {
          datas?.clear();
          datas = value.Data;
          equipmentResponseData?.hardwareDatas = datas; //记录五金数据
          var length = datas?.length ?? 0;
          //五金列表数据================567
          // print("五金列表数据================$length");
          if (length <= 0) {
            AppDialog.showDialogWithInfo(context,
                    content: AppStrings.of(context).noData) //暂无数据
                ?.then((value) {});
          } else {
            // print(
            //     "_setState: ${UiForm1?._setState}\tsetStateBody :${setStateBody}");
            // setStateBody?.call(() {}); //刷新
            UiForm1._tableSetState?.call(() {}); //表格刷新。
            // UiForm1?._setState?.call((){});
            callbackWithBool?.call(true);
          }
        } catch (e) {}
      } else {
        //异常
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
            ?.then((value) {});
      }
    });
  }
}
